<?php
/**
 * Created by PhpStorm.
 * User: zhangxilu
 * Date: 2017/12/20
 * Time: 下午9:01
 */

namespace frontend\common;


use yii\web\Controller;

class ApiController extends Controller
{
    public $layout = false;

    /**
     * 成功
     *
     * @param array $data 成功需要输出的数据
     *
     * @return \yii\web\Response
     */
    protected function success(array $data)
    {
        return $this->send('success', $data);
    }

    /**
     * 错误
     *
     * @param string $message
     *
     * @return \yii\web\Response
     */
    protected function error($message = '')
    {
        return $this->send('error', [], $message);
    }

    /**
     * @param string $code
     * @param array  $data
     * @param string $message
     *
     * @return \yii\web\Response
     */
    protected function send($code, $data, $message = '')
    {
        return $this->asJson(['code' => $code, 'data' => $data, 'message' => $message]);
    }

    /**
     * 分页页码
     * @return int
     */
    protected function getPage()
    {
        $page = \Yii::$app->request->get('page', 1);
        if (!empty($page) && $page > 1) {
            return $page;
        }

        return 1;
    }

    /**
     * 分页大小
     * @param int $default 默认大小
     * @return int
     */
    protected function getPageSize($default = 20)
    {
        $pageSize = \Yii::$app->request->get('pageSize', $default);
        if ($pageSize < 1) {
            return 1;
        }
        if ($pageSize > 100) {
            return 100;
        }

        return $pageSize;
    }

}